import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WordTableDataProcessor {

    /**
     * 处理Word表格中“处理方法”列的数据
     * @param inputFilePath 输入Word文件路径
     * @param outputFilePath 输出处理后的Word文件路径
     */
    public static void processWordTable(String inputFilePath, String outputFilePath) {
        try (XWPFDocument document = new XWPFDocument(new FileInputStream(inputFilePath))) {
            // 遍历所有表格
            for (XWPFTable table : document.getTables()) {
                int methodColumnIndex = -1;
                // 获取表头行，查找“处理方法”列的索引
                XWPFTableRow headerRow = table.getRow(0);
                for (int i = 0; i < headerRow.getTableCells().size(); i++) {
                    String cellText = headerRow.getCell(i).getText();
                    if ("处理方法".equals(cellText.trim())) {
                        methodColumnIndex = i;
                        break;
                    }
                }

                // 如果找到“处理方法”列，处理该列数据
                if (methodColumnIndex != -1) {
                    // 从第二行开始处理数据行（跳过表头）
                    for (int i = 1; i < table.getRows().size(); i++) {
                        XWPFTableRow dataRow = table.getRow(i);
                        if (dataRow.getTableCells().size() > methodColumnIndex) {
                            XWPFTableCell methodCell = dataRow.getCell(methodColumnIndex);
//                            String originalText = methodCell.getText();
                            // 执行替换操作
                            String originalText = getCellText(methodCell);
                            String processedText = replaceText(originalText);
                            System.out.println("<code>"+processedText+"</code>");
                            System.out.println();
                            // 清空单元格原有内容并设置处理后的内容
                            methodCell.removeParagraph(0);
                            XWPFParagraph paragraph = methodCell.addParagraph();
                            XWPFRun run = paragraph.createRun();
                            run.setText(processedText);
                        }
                    }
                }
            }

            // 保存处理后的文档
            try (FileOutputStream out = new FileOutputStream(outputFilePath)) {
                document.write(out);
            }
            System.out.println("Word表格数据处理完成，已保存至：" + outputFilePath);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
 * 正确读取单元格内容，保留换行和空格
 */
private static String getCellText(XWPFTableCell cell) {
    if (cell == null) {
        return "";
    }
    StringBuilder textBuilder = new StringBuilder();
    // 遍历单元格内的所有段落
    for (int i = 0; i < cell.getParagraphs().size(); i++) {
        XWPFParagraph paragraph = cell.getParagraphs().get(i);
        // 遍历段落内的所有文本运行
        for (XWPFRun run : paragraph.getRuns()) {
            textBuilder.append(run.getText(0)); // 获取文本内容
        }
        // 段落间添加换行符（除最后一个段落外）
        if (i != cell.getParagraphs().size() - 1) {
            textBuilder.append("\r\n");
        }
    }
    return textBuilder.toString();
}
    /**
     * 按照规则替换字符串
     * @param text 原始字符串
     * @return 处理后的字符串
     */
    private static String replaceText(String text) {
        if (text == null) {
            return "";
        }
        // 先将四个空格替换为&nbsp;
        String processed = text.replaceAll(" {4}", "&nbsp;");
        // 再将\r\n替换为<br/>
        processed = processed.replaceAll("\r\n", "<br/>");
        // 最后将|替换为\|
        processed = processed.replaceAll("\\|", "\\\\|");
        return processed;
    }

    // 使用示例
    public static void main(String[] args) {
        String inputPath = "D:\\project\\sgchen-security\\数据传输加解密及数据存储加解密使用手册.docx";  // 输入Word文件路径
        String outputPath = "D:\\project\\sgchen-security\\output.docx";  // 输出处理后的Word文件路径
        processWordTable(inputPath, outputPath);
    }
}